package triannon.client.sprites;

import java.util.HashMap;
import java.util.Iterator;

import org.jdom.Element;

import triannon.client.interfaces.IXML;
import triannon.client.util.ResourceLocator;
import triannon.client.util.XMLIO;

public class AnimationMap implements IXML {
	private final HashMap<AnimationKey, Animation> map = new HashMap<AnimationKey, Animation>();
	private AnimationKey defaultKey = null;
	private final String spriteKey;
	private final SpriteType spriteType;

	public AnimationMap(SpriteType spriteType, String spriteKey, Element element) {
		this.spriteType = spriteType;
		this.spriteKey = spriteKey;
		parseXML(element);
	}

	@Override
	public void parseXML(Element element) {
		Iterator<?> it = element.getChildren("animation").iterator();

		while (it.hasNext()) {
			Element animElem = (Element) it.next();
			Animation anim = new Animation(spriteType, spriteKey, animElem);

			map.put(anim.getKey(), anim);
			if (anim.isDefaultAnimation()) {
				defaultKey = anim.getKey();
			}
		}
	}

	public Animation get(AnimationKey animationKey) {
		return map.get(animationKey);
	}

	public Animation getDefault() {
		return map.get(defaultKey);
	}

	@Override
	public Element toXML() {
		throw new UnsupportedOperationException("Xml output not supported");
	}

	public static void main(String[] args) {
		ResourceLocator.addResourceDir("triannon/client/resource/sprites/");
		Element rootElem = XMLIO.readXML(ResourceLocator.getResource("unit.xml"));

		Element anim = rootElem.getChild("sprite");

		AnimationMap map = new AnimationMap(SpriteType.UNIT, "grunt", anim);

		System.err.println(map.get(AnimationKey.STAND_DOWN));
		System.err.println(map.getDefault());
	}

}
